package sk.stuba.fiit.foo07.genex.gui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import sk.stuba.fiit.foo07.genex.beans.Category;
import sk.stuba.fiit.foo07.genex.beans.Keyword;
import sk.stuba.fiit.foo07.genex.beans.Test;
import sk.stuba.fiit.foo07.genex.common.ResourceHelper;
import sk.stuba.fiit.foo07.genex.dao.CategoryDao;
import sk.stuba.fiit.foo07.genex.dao.CategoryDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionDao;
import sk.stuba.fiit.foo07.genex.dao.QuestionDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDao;
import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDaoDerby;
import sk.stuba.fiit.foo07.genex.exceptions.NotEnoughQuestionsException;
import sk.stuba.fiit.foo07.genex.generator.TestGenerator;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class GenerateTestDialog extends javax.swing.JDialog {

    /**
     * 
     */
    private static final long serialVersionUID = 92194243772639229L;

    private ResourceHelper resHelp;
    private DefaultMutableTreeNode rootNode;
    private DefaultListModel keywords;
    private Connection connection;
    private CategoryDao cDao;
    private QuestionDao qDao;
    private QuestionTypeDao qtDao;
    private CheckBoxTreeCellRenderer treeRenderer;

    private Test generatedTest;

    private ArrayList<Integer> difficultiesCount;
    private LinkedList<Integer> questionCategoryIDs;
    private ArrayList<Integer> keywordIDs;
    private LinkedList<Integer> questionTypeIDs;
    private int questionCount;
    private int pointsSummDesired;

    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    private JScrollPane jScrollPane3;
    private JLabel jLabel6;
    private JLabel jLabel5;
    private JCheckBox jChbEssay;
    private JList jLstKeywords;
    private JLabel jLabel12;
    private ButtonGroup buttonGroup1;
    private JSpinner jSpinner5;
    private JSpinner jSpinner4;
    private JSpinner jSpinner3;
    private JSpinner jSpinner2;
    private JSpinner jSpinner1;
    private JLabel jLabel11;
    private JLabel jLabel10;
    private JLabel jLabel9;
    private JLabel jLabel8;
    private JLabel jLabel7;
    private JRadioButton jRadioButtonComplexityCount;
    private JRadioButton jRadioButtonAvgComplexity;
    private JLabel jLabel2;
    private JComboBox jCbxDiff;
    private ProgressCellRenderer jPbrDiff;
    private JButton jBtnNewKeyword;
    private JButton jBtnDeletePicture;
    private JCheckBox jChbPicturesToo;
    private JCheckBox jChbFillIn;
    private JCheckBox jChbTrueFalse;
    private JCheckBox jChbMulti;
    private JCheckBox jChbSingle;
    private JTextField jTfdPoints;
    private JLabel jLabel4;
    private JTextField jTfdQuestionCount;
    private JLabel jLabel3;
    private JLabel jLblQCount;
    private JLabel jLabel1;
    private JButton jBtnOK;
    private JButton jBtnCancel;
    private JTree jTreeCategories;
    private JSeparator jSeparator2;
    private JSeparator jSeparator1;
    private JTextPane jTxtHint;

    private int retVal = javax.swing.JOptionPane.CANCEL_OPTION;

    /**
     * @return the generatedTest
     */
    public Test getGeneratedTest() {
        return generatedTest;
    }

    public GenerateTestDialog(JFrame frame, Connection c) {
        super(frame);

        resHelp = new ResourceHelper();
        connection = c;
        try {
            cDao = new CategoryDaoDerby(c);
            qDao = new QuestionDaoDerby(c);
            qtDao = new QuestionTypeDaoDerby(c);
            Category root = cDao.getRootCategories().get(0);
            rootNode = new DefaultMutableTreeNode(new CheckBoxCategory(root));
            keywords = new DefaultListModel();
            createTree(rootNode, root.getCategoryID());
        } catch (SQLException e) {
            hint("Error: " + e.getMessage());
        }
        initGUI();
    }

    private void createTree(DefaultMutableTreeNode node, Integer cID) {
        ArrayList<Category> cats = null;
        try {
            cats = cDao.getCategoriesByParentID(cID);
            for (Category subc : cats) {
                CheckBoxCategory sc = new CheckBoxCategory(subc);
                DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(sc);
                node.add(subNode);
                createTree(subNode, sc.getCategoryID());
            }
        } catch (SQLException e) {
            hint(e.getMessage());
        }
    }

    private void initGUI() {
        try {
            // START >> this
            this.setTitle("Generova\u0165 test");
            getContentPane().setLayout(null);
            this.setResizable(false);
            setLocationByPlatform(true);
            // START >> jScrollPane1
            jScrollPane1 = new JScrollPane();
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(10, 11, 710, 56);
            // START >> jTxtHint
            jTxtHint = new JTextPane();
            jScrollPane1.setViewportView(jTxtHint);
            hint("Info: Hints");
            jTxtHint.setEditable(false);
            jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
            jTxtHint.setPreferredSize(new java.awt.Dimension(682, 53));
            // END << jTxtHint
            // END << jScrollPane1
            // START >> jSeparator1
            jSeparator1 = new JSeparator();
            getContentPane().add(jSeparator1);
            jSeparator1.setBounds(10, 73, 710, 12);
            // END << jSeparator1
            // START >> jSeparator2
            jSeparator2 = new JSeparator();
            getContentPane().add(jSeparator2);
            jSeparator2.setBounds(14, 435, 702, 6);
            // END << jSeparator2
            // START >> jScrollPane2
            jScrollPane2 = new JScrollPane();
            getContentPane().add(jScrollPane2);
            jScrollPane2.setBounds(10, 106, 208, 297);
            // START >> jTreeCategories
            jTreeCategories = new JTree(rootNode);
            jScrollPane2.setViewportView(jTreeCategories);
            treeRenderer = new CheckBoxTreeCellRenderer();
            jTreeCategories.setCellRenderer(treeRenderer);
            jTreeCategories.setEditable(false);
            jTreeCategories.setBackground(new java.awt.Color(255, 255, 240));
            jTreeCategories.setPreferredSize(new java.awt.Dimension(170, 214));
            jTreeCategories.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    jTreeCategoriesMouseClicked(evt);
                }
            });
            // END << jTreeCategories
            // END << jScrollPane2
            // START >> jBtnCancel
            jBtnCancel = new JButton();
            getContentPane().add(jBtnCancel);
            jBtnCancel.setText("Cancel");
            jBtnCancel.setBounds(606, 447, 111, 23);
            jBtnCancel.setMnemonic(java.awt.event.KeyEvent.VK_C);
            jBtnCancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnCancelActionPerformed(evt);
                }
            });
            // END << jBtnCancel
            // START >> jBtnOK
            jBtnOK = new JButton();
            getContentPane().add(jBtnOK);
            jBtnOK.setText("OK");
            jBtnOK.setBounds(490, 447, 111, 23);
            jBtnOK.setMnemonic(java.awt.event.KeyEvent.VK_O);
            jBtnOK.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jBtnOKActionPerformed(evt);
                }
            });
            // END << jBtnOK
            // START >> jLabel1
            jLabel1 = new JLabel();
            getContentPane().add(jLabel1);
            jLabel1.setText("Po\u010det vybraných otázok");
            jLabel1.setBounds(12, 409, 155, 14);
            jLabel1.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel1
            // START >> jLblQCount
            jLblQCount = new JLabel();
            getContentPane().add(jLblQCount);
            jLblQCount.setText("0");
            jLblQCount.setBounds(179, 409, 41, 14);
            jLblQCount.setHorizontalAlignment(SwingConstants.RIGHT);
            jLblQCount.setForeground(new java.awt.Color(0, 0, 255));
            // END << jLblQCount
            // START >> jLabel3
            jLabel3 = new JLabel();
            getContentPane().add(jLabel3);
            jLabel3.setText("Po\u010det otázok");
            jLabel3.setBounds(508, 105, 91, 14);
            jLabel3.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel3
            // START >> jTfdQuestionCount
            jTfdQuestionCount = new JTextField();
            getContentPane().add(jTfdQuestionCount);
            jTfdQuestionCount.setText("0");
            jTfdQuestionCount.setBounds(681, 99, 35, 18);
            jTfdQuestionCount.setHorizontalAlignment(SwingConstants.RIGHT);
            jTfdQuestionCount.setBackground(new java.awt.Color(255, 255, 240));
            jTfdQuestionCount.setForeground(new java.awt.Color(0, 0, 255));
            // END << jTfdQuestionCount
            // START >> jLabel4
            jLabel4 = new JLabel();
            getContentPane().add(jLabel4);
            jLabel4.setText("Po\u010det bodov");
            jLabel4.setBounds(508, 125, 84, 14);
            jLabel4.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel4
            // START >> jTfdPoints
            jTfdPoints = new JTextField();
            getContentPane().add(jTfdPoints);
            jTfdPoints.setText("0");
            jTfdPoints.setBounds(681, 123, 35, 18);
            jTfdPoints.setHorizontalAlignment(SwingConstants.RIGHT);
            jTfdPoints.setBackground(new java.awt.Color(255, 255, 240));
            jTfdPoints.setForeground(new java.awt.Color(0, 0, 255));
            jTfdPoints.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    hint("Info: Ak je hodnota poľa rovná nule, počet bodov pre otázky vo vygenerovanom teste bude \n rovný ich obtiažnosti.");
                }
            });
            // END << jTfdPoints
            // START >> jChbSingle
            jChbSingle = new JCheckBox();
            getContentPane().add(jChbSingle);
            jChbSingle.setText("Single choice");
            jChbSingle.setBounds(517, 173, 111, 23);
            jChbSingle.setSelected(true);
            // END << jChbSingle
            // START >> jChbMulti
            jChbMulti = new JCheckBox();
            getContentPane().add(jChbMulti);
            jChbMulti.setText("Multi choice");
            jChbMulti.setBounds(517, 195, 117, 23);
            jChbMulti.setSelected(true);
            // END << jChbMulti
            // START >> jChbTrueFalse
            jChbTrueFalse = new JCheckBox();
            getContentPane().add(jChbTrueFalse);
            jChbTrueFalse.setText("True/False");
            jChbTrueFalse.setBounds(518, 219, 117, 23);
            jChbTrueFalse.setSelected(true);
            // END << jChbTrueFalse
            // START >> jChbFillIn
            jChbFillIn = new JCheckBox();
            getContentPane().add(jChbFillIn);
            jChbFillIn.setText("Fill in");
            jChbFillIn.setBounds(634, 173, 74, 23);
            jChbFillIn.setSelected(true);
            // END << jChbFillIn
            // START >> jChbEssay
            jChbEssay = new JCheckBox();
            getContentPane().add(jChbEssay);
            jChbEssay.setText("Essay");
            jChbEssay.setBounds(634, 195, 69, 26);
            jChbEssay.setSelected(true);
            // END << jChbEssay
            // START >> jLabel5
            jLabel5 = new JLabel();
            getContentPane().add(jLabel5);
            jLabel5.setBounds(508, 153, 208, 95);
            TitledBorder border = BorderFactory
                    .createTitledBorder("Typy otázok");
            border.setTitleColor(new Color(49, 106, 196));
            jLabel5.setBorder(border);
            jLabel5.setHorizontalAlignment(SwingConstants.LEFT);
            jLabel5.setHorizontalTextPosition(SwingConstants.LEFT);
            jLabel5.setVerticalAlignment(SwingConstants.TOP);
            jLabel5.setVerticalTextPosition(SwingConstants.TOP);
            // END << jLabel5
            // START >> jLabel6
            jLabel6 = new JLabel();
            getContentPane().add(jLabel6);
            jLabel6.setText("K\u013eú\u010dové slová:");
            jLabel6.setBounds(509, 254, 161, 15);
            jLabel6.setForeground(new java.awt.Color(100, 0, 0));
            // END << jLabel6
            // START >> jScrollPane3
            jScrollPane3 = new JScrollPane();
            getContentPane().add(jScrollPane3);

            jScrollPane3.setBounds(508, 275, 210, 123);
            {
                jChbPicturesToo = new JCheckBox();
                getContentPane().add(jChbPicturesToo);
                jChbPicturesToo.setText("Vybera\u0165 aj otázky s obrázkami");
                jChbPicturesToo.setBounds(258, 407, 250, 18);
                jChbPicturesToo.setForeground(new java.awt.Color(100, 0, 0));
                jChbPicturesToo.setSelected(true);
                jChbPicturesToo.setMnemonic(java.awt.event.KeyEvent.VK_V);
            }
            {
                jBtnDeletePicture = new JButton();
                getContentPane().add(jBtnDeletePicture);
                jBtnDeletePicture.setIcon(new ImageIcon(new ResourceHelper()
                        .getResourceBytes("/icons/remove.png")));
                jBtnDeletePicture.setActionCommand("picOdstráni\u0165");
                jBtnDeletePicture
                        .setHorizontalTextPosition(SwingConstants.CENTER);
                jBtnDeletePicture
                        .setVerticalTextPosition(SwingConstants.BOTTOM);
                jBtnDeletePicture.setToolTipText("Odstráni\u0165");
                jBtnDeletePicture.setBounds(696, 404, 21, 21);
                jBtnDeletePicture.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jBtnDeleteKeywordActionPerformed(evt);
                    }
                });
            }
            {
                jBtnNewKeyword = new JButton();
                getContentPane().add(jBtnNewKeyword);
                jBtnNewKeyword.setIcon(new ImageIcon(new ResourceHelper()
                        .getResourceBytes("/icons/add.png")));
                jBtnNewKeyword.setActionCommand("ksNové");
                jBtnNewKeyword.setHorizontalTextPosition(SwingConstants.CENTER);
                jBtnNewKeyword.setVerticalTextPosition(SwingConstants.BOTTOM);
                jBtnNewKeyword.setToolTipText("Nové");
                jBtnNewKeyword.setBounds(670, 404, 21, 21);
                jBtnNewKeyword.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jBtnNewKeywordActionPerformed(evt);
                    }
                });
            }
            {
                ComboBoxModel jTfdDifficultyModel = new DefaultComboBoxModel(
                        new String[] { "NA", "1", "2", "3", "4", "5" });
                jCbxDiff = new JComboBox();
                getContentPane().add(jCbxDiff);
                jCbxDiff.setModel(jTfdDifficultyModel);
                jCbxDiff.setBounds(435, 163, 45, 21);
                jCbxDiff.setBackground(new java.awt.Color(255, 255, 240));
                jCbxDiff.setForeground(new java.awt.Color(0, 0, 255));
                jCbxDiff.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        int indexSelected = jCbxDiff.getSelectedIndex();
                        if (indexSelected == 0) {
                            disableProgressBar();
                        } else {
                            enableProgressBar();
                            jPbrDiff.setIntegerValue(indexSelected);
                        }
                    }
                });
            }
            {
                jPbrDiff = new ProgressCellRenderer();
                getContentPane().add(jPbrDiff);
                jPbrDiff.setBounds(259, 163, 170, 21);

                jPbrDiff.setIntegerValue(0);
                jPbrDiff.setFocusable(false);
                jPbrDiff.setRequestFocusEnabled(false);
                jPbrDiff.addMouseListener(new ProgressbarMouseHandler(jPbrDiff,
                        jCbxDiff, 1));
            }
            {
                jLstKeywords = new JList();
                //getContentPane().add(jLstKeywords);
                jScrollPane3.setViewportView(jLstKeywords);

                jLstKeywords.setModel(keywords);
                jLstKeywords.setBackground(new java.awt.Color(255, 255, 240));
                jLstKeywords.setBounds(228, 408, 267, 93);
                jLstKeywords.setPreferredSize(new java.awt.Dimension(145, 80));
                jLstKeywords.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent evt) {
                        if (evt.getClickCount() == 1)
                            hint("Info: Dvojklikom môžete vybrané kľúčové slovo vymazať.");
                        else
                            jBtnDeleteKeywordActionPerformed(new ActionEvent(
                                    jLstKeywords, 0, null));
                    }
                });
            }
            {
                jLabel2 = new JLabel();
                getContentPane().add(jLabel2);
                jLabel2.setBounds(226, 99, 274, 304);
                border = BorderFactory.createTitledBorder("Spôsob generovania");
                border.setTitleColor(new Color(49, 106, 196));
                jLabel2.setBorder(border);
            }
            {
                jRadioButtonAvgComplexity = new JRadioButton();
                getContentPane().add(jRadioButtonAvgComplexity);
                jRadioButtonAvgComplexity
                        .setText("Priemerná zlo\u017eitos\u0165 otázok");
                jRadioButtonAvgComplexity.setBounds(240, 135, 214, 19);
                jRadioButtonAvgComplexity.setForeground(new java.awt.Color(100,
                        0, 0));
                jRadioButtonAvgComplexity.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent evt) {
                        jRadioButton1ItemStateChanged(evt);
                    }
                });
                getButtonGroup1().add(jRadioButtonAvgComplexity);
                getButtonGroup1().setSelected(
                        jRadioButtonAvgComplexity.getModel(), true);
            }
            {
                jRadioButtonComplexityCount = new JRadioButton();
                getContentPane().add(jRadioButtonComplexityCount);
                jRadioButtonComplexityCount
                        .setText("Ur\u010denie po\u010dtu otázok s obtia\u017enos\u0165ou");
                jRadioButtonComplexityCount.setBounds(240, 206, 250, 19);
                jRadioButtonComplexityCount.setForeground(new java.awt.Color(
                        100, 0, 0));
                jRadioButtonComplexityCount.addItemListener(new ItemListener() {

                    public void itemStateChanged(ItemEvent evt) {
                        jRadioButton2ItemStateChanged(evt);
                    }
                });
                getButtonGroup1().add(jRadioButtonComplexityCount);
            }
            {
                jLabel7 = new JLabel();
                getContentPane().add(jLabel7);
                jLabel7.setText("obtia\u017enos\u0165 1");
                jLabel7.setBounds(260, 237, 84, 15);
                jLabel7.setForeground(new java.awt.Color(0, 0, 0));
            }
            {
                jLabel8 = new JLabel();
                getContentPane().add(jLabel8);
                jLabel8.setText("obtia\u017enos\u0165 2");
                jLabel8.setBounds(260, 268, 82, 15);
                jLabel8.setForeground(new java.awt.Color(0, 0, 0));
            }
            {
                jLabel9 = new JLabel();
                getContentPane().add(jLabel9);
                jLabel9.setText("obtia\u017enos\u0165 3");
                jLabel9.setBounds(260, 299, 85, 15);
                jLabel9.setForeground(new java.awt.Color(0, 0, 0));
            }
            {
                jLabel10 = new JLabel();
                getContentPane().add(jLabel10);
                jLabel10.setText("obtia\u017enos\u0165 4");
                jLabel10.setBounds(258, 330, 87, 15);
                jLabel10.setForeground(new java.awt.Color(0, 0, 0));
            }
            {
                jLabel11 = new JLabel();
                getContentPane().add(jLabel11);
                jLabel11.setText("obtia\u017enos\u0165 5");
                jLabel11.setBounds(258, 361, 87, 15);
                jLabel11.setForeground(new java.awt.Color(0, 0, 0));
            }
            {
                SpinnerNumberModel jSpinnerModel = new SpinnerNumberModel();
                jSpinnerModel.setMinimum(0);
                jSpinner1 = new JSpinner();
                getContentPane().add(jSpinner1);
                jSpinner1.setModel(jSpinnerModel);
                jSpinner1.setBounds(349, 234, 55, 22);
                jSpinner1.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        jSpinnerStateChanged(evt);
                    }
                });
                jSpinner1.setEnabled(false);
                jSpinner1.getEditor().setBackground(
                        new java.awt.Color(255, 255, 240));
            }
            {
                SpinnerNumberModel jSpinnerModel = new SpinnerNumberModel();
                jSpinnerModel.setMinimum(0);
                jSpinner2 = new JSpinner();
                getContentPane().add(jSpinner2);
                jSpinner2.setModel(jSpinnerModel);
                jSpinner2.setBounds(349, 265, 55, 22);
                jSpinner2.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        jSpinnerStateChanged(evt);
                    }
                });
                jSpinner2.setEnabled(false);
                jSpinner2.getEditor().setBackground(
                        new java.awt.Color(255, 255, 240));
            }
            {
                SpinnerNumberModel jSpinnerModel = new SpinnerNumberModel();
                jSpinnerModel.setMinimum(0);
                jSpinner3 = new JSpinner();
                getContentPane().add(jSpinner3);
                jSpinner3.setModel(jSpinnerModel);
                jSpinner3.setBounds(349, 296, 55, 22);
                jSpinner3.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        jSpinnerStateChanged(evt);
                    }
                });
                jSpinner3.setEnabled(false);
                jSpinner3.getEditor().setBackground(
                        new java.awt.Color(255, 255, 240));
            }
            {
                SpinnerNumberModel jSpinnerModel = new SpinnerNumberModel();
                jSpinnerModel.setMinimum(0);
                jSpinner4 = new JSpinner();
                getContentPane().add(jSpinner4);
                jSpinner4.setModel(jSpinnerModel);
                jSpinner4.setBounds(349, 327, 55, 22);
                jSpinner4.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        jSpinnerStateChanged(evt);
                    }
                });
                jSpinner4.setEnabled(false);
                jSpinner4.getEditor().setBackground(
                        new java.awt.Color(255, 255, 240));
            }
            {
                SpinnerNumberModel jSpinnerModel = new SpinnerNumberModel();
                jSpinnerModel.setMinimum(0);
                jSpinner5 = new JSpinner();
                getContentPane().add(jSpinner5);
                getContentPane().add(getJLabel12());
                jSpinner5.setModel(jSpinnerModel);
                jSpinner5.setBounds(349, 358, 55, 22);
                jSpinner5.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        jSpinnerStateChanged(evt);
                    }
                });
                jSpinner5.setEnabled(false);
                jSpinner5.getEditor().setBackground(
                        new java.awt.Color(255, 255, 240));
            }
            // START >> jTxtKeywords
            // END << jTxtKeywords
            // END << jScrollPane3
            // END << this
            this.setSize(734, 511);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hint(String text) {
        if (jTxtHint.getBackground() == GenexGUI.COMB1_BACKGROUND_COLOR) {
            jTxtHint.setBackground(GenexGUI.COMB2_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB2_FOREGROUND_COLOR);
        } else {
            jTxtHint.setBackground(GenexGUI.COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(GenexGUI.COMB1_FOREGROUND_COLOR);
        }
        if (text.startsWith("Error:")) {
            jTxtHint.setText(text.substring(6));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/error.png")));
        } else if (text.startsWith("Warning:")) {
            jTxtHint.setText(text.substring(8));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/warning.png")));
        } else if (text.startsWith("Info:")) {
            jTxtHint.setText(text.substring(5));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/info.png")));
        } else {
            jTxtHint.setText(text);
        }
    }

    private void getSelectedCategories(DefaultMutableTreeNode node) {
        CheckBoxCategory cc = (CheckBoxCategory) node.getUserObject();
        if (cc.isSelected()) {
            questionCategoryIDs.add(cc.getCategoryID());
        }
        for (int i = 0; i < node.getChildCount(); i++) {
            getSelectedCategories((DefaultMutableTreeNode) node.getChildAt(i));
        }
    }

    private void getQuestionTypes() {
        try {
            if (jChbTrueFalse.isSelected()) {
                questionTypeIDs.add(qtDao.getQuestionTypeByName(jChbTrueFalse
                        .getText()));
            }
            if (jChbSingle.isSelected()) {
                questionTypeIDs.add(qtDao.getQuestionTypeByName(jChbSingle
                        .getText()));
            }
            if (jChbMulti.isSelected()) {
                questionTypeIDs.add(qtDao.getQuestionTypeByName(jChbMulti
                        .getText()));
            }
            if (jChbEssay.isSelected()) {
                questionTypeIDs.add(qtDao.getQuestionTypeByName(jChbEssay
                        .getText()));
            }
            if (jChbFillIn.isSelected()) {
                questionTypeIDs.add(qtDao.getQuestionTypeByName(jChbFillIn
                        .getText()));
            }
        } catch (SQLException sqle) {
            hint("Error: Chyba databázy: " + sqle.getMessage());
        }

    }

    private void getSelectedKeywords() {
        Keyword k;
        for (int i = 0; i < keywords.getSize(); i++) {
            k = (Keyword) keywords.get(i);
            keywordIDs.add(k.getKeywordID());
        }
    }

    private void jBtnOKActionPerformed(ActionEvent evt) {
        retVal = javax.swing.JOptionPane.OK_OPTION;
        questionCategoryIDs = new LinkedList<Integer>();
        keywordIDs = new ArrayList<Integer>(keywords.size());
        questionTypeIDs = new LinkedList<Integer>();

        //this is because the rootNode does not represent real category with ID(its just gui element) 
        for (int i = 0; i < rootNode.getChildCount(); i++) {
            getSelectedCategories((DefaultMutableTreeNode) rootNode
                    .getChildAt(i));
        }
        if (questionCategoryIDs.size() == 0) {
            hint("Warning: Musi byt vybrana aspon jedna kategoria!");
            return;
        }

        getSelectedKeywords();

        getQuestionTypes();

        try {
            questionCount = new Integer(jTfdQuestionCount.getText());
        } catch (NumberFormatException e1) {
            hint("Warning: Počet otázok musí byť celé číslo!");
            return;
        }
        if (questionCount <= 0) {
            hint("Warning: Počet otazok v teste musi byť väčší ako 0!");
            return;
        }

        try {
            pointsSummDesired = new Integer(jTfdPoints.getText());
        } catch (NumberFormatException e1) {
            hint("Warning: Počet bodov musí byť celé číslo!");
            return;
        }
        if (pointsSummDesired < 0) {
            hint("Warning: Počet bodov za test musi byť väčší rovné nule!");
            return;
        }

        try {
            if (jRadioButtonComplexityCount.isSelected()) {
                int sum = 0;
                int count = 0;
                difficultiesCount = new ArrayList<Integer>(5);

                count = ((SpinnerNumberModel) jSpinner1.getModel()).getNumber()
                        .intValue();
                difficultiesCount.add(0, count);
                sum += count;
                count = ((SpinnerNumberModel) jSpinner2.getModel()).getNumber()
                        .intValue();
                difficultiesCount.add(1, count);
                sum += count;
                count = ((SpinnerNumberModel) jSpinner3.getModel()).getNumber()
                        .intValue();
                difficultiesCount.add(2, count);
                sum += count;
                count = ((SpinnerNumberModel) jSpinner4.getModel()).getNumber()
                        .intValue();
                difficultiesCount.add(3, count);
                sum += count;
                count = ((SpinnerNumberModel) jSpinner5.getModel()).getNumber()
                        .intValue();
                difficultiesCount.add(4, count);
                sum += count;

                if (sum > questionCount) {
                    hint("Warning: Počet otázok je menší ako súčet počtov jednotlivých obtiažností");
                    return;
                }

                TestGenerator tg = new TestGenerator(connection,
                        new ArrayList<Integer>(questionCategoryIDs),
                        keywordIDs, new ArrayList<Integer>(questionTypeIDs),
                        questionCount, pointsSummDesired, jChbPicturesToo
                                .isSelected(), difficultiesCount);

                tg.assembleTest();
                generatedTest = tg.getGeneratedTest();
            } else {
                TestGenerator tg = new TestGenerator(connection,
                        new ArrayList<Integer>(questionCategoryIDs),
                        keywordIDs, new ArrayList<Integer>(questionTypeIDs),
                        jCbxDiff.getSelectedIndex(), questionCount,
                        pointsSummDesired, jChbPicturesToo.isSelected());

                tg.generateTest();
                generatedTest = tg.getGeneratedTest();
            }
        } catch (NotEnoughQuestionsException e) {
            hint("Error: " + e.getMessage());
            return;
        } catch (SQLException e) {
            hint("Error: Chyba v databáze: " + e.getMessage());
            return;
        }

        setVisible(false);
    }

    private void jBtnCancelActionPerformed(ActionEvent evt) {
        retVal = javax.swing.JOptionPane.CANCEL_OPTION;

        setVisible(false);
    }

    public int showDialog() {
        setModalityType(ModalityType.APPLICATION_MODAL);

        setVisible(true);

        return retVal;
    }

    public void setQuestionCount(int count) {
        System.out.println("" + count);
        jLblQCount.setText("" + count);
    }

    private boolean hasKeyword(Keyword k) {
        for (int i = 0; i < keywords.size(); i++)
            if (k.getText().equals(((Keyword) (keywords.get(i))).getText()))
                return true;

        return false;
    }

    private void jBtnNewKeywordActionPerformed(ActionEvent evt) {
        boolean hasDuplicity = false;
        NewKeywordDialog nkd = new NewKeywordDialog(this, connection);
        nkd.deactivateNewKeywordAdding();
        nkd.setLocationRelativeTo(null);
        Keyword[] k = nkd.showDialog();
        if (k != null) {
            for (int i = 0; i < k.length; i++)
                if (hasKeyword(k[i]) == false)
                    keywords.addElement(k[i]);
                else {
                    hasDuplicity = true;
                }
        }
        if (hasDuplicity)
            hint("Info: Niektoré kľúčové slová neboli pridané, lebo sa v zozname už nachádzajú.");
        else
            hint("Info: Všetky vybrané kľúčové slová boli úspešne pridané.");
    }

    private void jBtnDeleteKeywordActionPerformed(ActionEvent evt) {
        int sel = jLstKeywords.getSelectedIndex();

        if (sel == -1) {
            hint("Warning: Najprv musíte vybrať kľúčové slová, ktoré chcete odstrániť.");
            return;
        }

        while (sel != -1) {
            keywords.remove(sel);
            sel = jLstKeywords.getSelectedIndex();
        }
    }

    private int getQuestionCount(DefaultMutableTreeNode from) {
        int pocet = 0;

        CheckBoxCategory cc = (CheckBoxCategory) from.getUserObject();
        try {
            if (cc.isSelected())
                pocet += qDao.getQuestionCount(cc.getCategoryID()); // zvysime pocet otazok
            int count = from.getChildCount();

            for (int i = 0; i < count; i++)
                // pocet otazok vstkych podkategorii
                pocet += getQuestionCount((DefaultMutableTreeNode) from
                        .getChildAt(i));
        } catch (SQLException e) {
            hint("Error: Zobrazený súčet otázok v kategóriách zrejme nie je správny: "
                    + e.getMessage());
        }

        return pocet;
    }

    private void setSubCategoriesSelected(DefaultMutableTreeNode from) {
        CheckBoxCategory sc = (CheckBoxCategory) from.getUserObject();
        sc.setSelected(true);
        int cc = from.getChildCount();

        for (int i = 0; i < cc; i++)
            setSubCategoriesSelected((DefaultMutableTreeNode) from
                    .getChildAt(i));
    }

    private void jTreeCategoriesMouseClicked(MouseEvent evt) {
        if (evt.getClickCount() == 2)
            return;

        TreePath tp = jTreeCategories
                .getPathForLocation(evt.getX(), evt.getY());
        if (tp == null)
            return;
        DefaultMutableTreeNode sel = (DefaultMutableTreeNode) tp
                .getLastPathComponent();

        CheckBoxCategory cc = (CheckBoxCategory) sel.getUserObject();
        cc.setSelected(!cc.isSelected());
        if (cc.isSelected())
            setSubCategoriesSelected(sel);

        setQuestionCount(getQuestionCount(rootNode));

        jTreeCategories.updateUI();
    }

    private ButtonGroup getButtonGroup1() {
        if (buttonGroup1 == null) {
            buttonGroup1 = new ButtonGroup();
        }
        return buttonGroup1;
    }

    private void disableProgressBar() {
        jCbxDiff.setSelectedIndex(0);
        jPbrDiff.setIntegerValue(0);
        /*
        jPbrDiff.setEnabled(false);
        for (MouseListener ml : jPbrDiff.getMouseListeners())
            jPbrDiff.removeMouseListener(ml);
         */
    }

    private void enableProgressBar() {
        //jPbrDiff.setEnabled(true);
        // jPbrDiff.addMouseListener(new ProgressbarMouseHandler(jPbrDiff,
        //       jCbxDiff));
    }

    private void jRadioButton1ItemStateChanged(ItemEvent evt) {
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            jCbxDiff.setEnabled(true);
            enableProgressBar();
        } else {
            jCbxDiff.setEnabled(false);
            disableProgressBar();
        }
    }

    private void jRadioButton2ItemStateChanged(ItemEvent evt) {
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            jSpinner1.setEnabled(true);
            jSpinner2.setEnabled(true);
            jSpinner3.setEnabled(true);
            jSpinner4.setEnabled(true);
            jSpinner5.setEnabled(true);
        } else {
            jSpinner1.setEnabled(false);
            jSpinner2.setEnabled(false);
            jSpinner3.setEnabled(false);
            jSpinner4.setEnabled(false);
            jSpinner5.setEnabled(false);
        }
    }

    private void jSpinnerStateChanged(ChangeEvent evt) {
        int sum = 0;

        sum += ((SpinnerNumberModel) jSpinner1.getModel()).getNumber()
                .intValue();
        sum += ((SpinnerNumberModel) jSpinner2.getModel()).getNumber()
                .intValue();
        sum += ((SpinnerNumberModel) jSpinner3.getModel()).getNumber()
                .intValue();
        sum += ((SpinnerNumberModel) jSpinner4.getModel()).getNumber()
                .intValue();
        sum += ((SpinnerNumberModel) jSpinner5.getModel()).getNumber()
                .intValue();

        if (sum > Integer.parseInt(jTfdQuestionCount.getText())) {
            jTfdQuestionCount.setText(String.valueOf(sum));
        }
    }

    private JLabel getJLabel12() {
        if (jLabel12 == null) {
            jLabel12 = new JLabel();
            jLabel12.setText("Kategórie");
            jLabel12.setBounds(12, 86, 72, 14);
            jLabel12.setForeground(new java.awt.Color(100, 0, 0));
        }
        return jLabel12;
    }
}
